package ui.activity;

import android.Manifest;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.fy.fyzf.R;
import com.fy.fyzf.base.BaseActivity;
import com.fy.fyzf.base.BaseFragment;
import com.fy.fyzf.bean.CheckWorkBean;
import com.fy.fyzf.bean.CheckWorkListBean;
import com.fy.fyzf.bean.BaseData;
import com.fy.fyzf.bean.IsInfoBean;
import com.fy.fyzf.bean.RandomTextBean;
import com.fy.fyzf.bean.WorkStepBean;
import com.fy.fyzf.glideUtils.GlideUtils;
import com.fy.fyzf.listener.PermissionListener;
import com.fy.fyzf.presenter.CheckWorkPresenter;
import com.fy.fyzf.utils.AppUtils;
import com.fy.fyzf.utils.DateUtils;
import com.fy.fyzf.utils.SPUtils;
import com.fy.fyzf.view.CheckWorkCallBack;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import ui.fragment.MyDemandFragment;
import ui.fragment.OffWorkFragment;
import ui.fragment.PeerFragment;
import ui.fragment.WorkCheckFragment;

public class WorkCheckActivity extends BaseActivity<CheckWorkPresenter> implements CheckWorkCallBack {


    public AMapLocationClientOption mLocationOption = null;
    public AMapLocationClient mLocationClient = null;
    private List<BaseFragment> fragmentList = new ArrayList<>();

    //mLocationOption
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);
//                    tvLocation.setText(amapLocation.getStreet()+amapLocation.getAoiName()  );
                    Log.e("定位", new Gson().toJson(amapLocation));
                    LatLng latLng=new LatLng(amapLocation.getLatitude(),amapLocation.getLongitude());
                    float distance = AMapUtils.calculateLineDistance(latLng,latLng2);
                    float qianmifload =(float) distance/1000;
                    lat = String.valueOf(amapLocation.getLatitude());
                    longStr = String.valueOf(amapLocation.getLongitude());
                    address = amapLocation.getStreet() +amapLocation.getAoiName();
                    if (null != workCheckFragment) {
                        workCheckFragment.setLocation(amapLocation.getStreet()+amapLocation.getAoiName());
                    }
                    if (null != workCheckFragment1) {
                        workCheckFragment1.setLocation(amapLocation.getStreet()+amapLocation.getAoiName());
                    }
                    if (null != offWorkFragment) {
                        offWorkFragment.setLocation(amapLocation.getStreet()+amapLocation.getAoiName());
                    }

                } else {
//                    AppUtils.showToast("定位异常");
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"+ amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getLocationDetail());
                }
            }
        }
    };
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.logo)
    ImageView logo;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.rl_record)
    RelativeLayout rlRecord;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
 /*   @BindView(R.id.tv_signin)
    TextView tvSignin;
    @BindView(R.id.tv_location)
    TextView tvLocation;*/
 private List<String> titles = new ArrayList<>();
    private WorkCheckFragment workCheckFragment;
    private WorkCheckFragment workCheckFragment1;
    private OffWorkFragment offWorkFragment;
    private LatLng latLng2;

    @Override
    protected CheckWorkPresenter createPresenter() {
        return new CheckWorkPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_work_check;
    }

    private int signInType = 4; //打卡类型
    public String lat = null;
    public String longStr = null;
    public String address;
    @Override
    public void initView() {
        super.initView();
        setTitleName("考勤");
        requestRuntimePermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionListener() {
            @Override
            public void onGranted() {
                //保存图片
//                downloadImg();
            }

            @Override
            public void onDenied(List<String> deniedPermissions) {
//              UIUtils.showToast(getString(R.string.write_storage_permission_deny));
                AppUtils.showToast("定位权限被拒绝，无法打卡");
                finish();
            }
        });
        initLocation();
//        tablayout.addTab(tablayout.newTab().setText("上班打卡"));
//        tablayout.addTab(tablayout.newTab().setText("外出打卡"));
//        tablayout.addTab(tablayout.newTab().setText("下班打卡"));
        viewPager.setOffscreenPageLimit(3);
        titles.add("上班打卡");
        titles.add("外出打卡");
        titles.add("下班打卡");
        workCheckFragment = WorkCheckFragment.newInstance(4, 1);
        workCheckFragment1 = WorkCheckFragment.newInstance(3, 2);
        offWorkFragment = OffWorkFragment.newInstance("", "");
        fragmentList.add(workCheckFragment);
        fragmentList.add(workCheckFragment1);
        fragmentList.add(offWorkFragment);

        LinearLayout linearLayout = (LinearLayout) tablayout.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerPadding(15);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.tablayout_divider_vertical));
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                if (tab.getPosition() == 0) {
                    signInType = 4;
//                    tvSignin.setText("上班打卡");
//                    tvSignin.setBackgroundResource(R.mipmap.icon_daka);
//                    tvLocation.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.icon_dingwei), null, null, null);

                } else if (tab.getPosition() == 1) {
//                    tvLocation.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.dingwei_red), null, null, null);
//                    tvSignin.setBackgroundResource(R.mipmap.daka_red);
//                    signInType = 3;
                } else {

//                    signInType = 5;
//                    tvSignin.setBackgroundResource(R.mipmap.daka_yellow);
//                    tvLocation.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.dingwei_yellow), null, null, null);
//                    tvSignin.setText("下班打卡");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                super.destroyItem(container, position, object);
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);

            }
        });
        tablayout.setupWithViewPager(viewPager);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (null != offWorkFragment) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                offWorkFragment.loadData1();
            }
        }).start();
    }
}

    @Override
    public void initData() {
        super.initData();
        String logoStr = SPUtils.getInstance(this).getString("logo", "");
        GlideUtils.loadCircleImage(logoStr,logo);
        tvName.setText(SPUtils.getInstance(this).getString("name", ""));

        mPresenter.getUserLocation();
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(false);
//        mLocationOption.setLocationCacheEnable(true);
        mLocationOption.setInterval(1000);
        mLocationOption.setNeedAddress(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.stopLocation();
        }

    }

    private CheckWorkBean checkWorkBean = new CheckWorkBean();
    @OnClick({R.id.logo, R.id.rl_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.logo:
                break;
            case R.id.rl_record:
                startActivity(new Intent(this,CheckWorkRecordActivity.class));
                break;
//            case R.id.tv_signin:
//                signIn();
//                break;
        }
    }

    @Override
    public void CheckWorkSuccess(BaseData baseData) {
        AppUtils.showToast("打卡成功");
    }

    @Override
    public void getCheckWorkListSuccess(CheckWorkListBean checkWorkListBean) {

    }

    @Override
    public void getWorkStepSuccess(WorkStepBean workStepBean) {

    }

    @Override
    public void addWorkLogSuccess(BaseData baseData) {

    }

    public double userLat;
    public double userLong;
    @Override
    public void getUserLocationSucccess(RandomTextBean randomTextBean) {
        latLng2 = new LatLng(Double.parseDouble(randomTextBean.getLatitude()),Double.parseDouble(randomTextBean.getLongitude()));
        userLat = Double.parseDouble(randomTextBean.getLatitude());
        userLong = Double.parseDouble(randomTextBean.getLongitude());
    }

    @Override
    public void isInfoSuccess(IsInfoBean isInfoBean) {

    }
}